(function(window) {
    function AJAX(options) {
      return new AJAX.prototype.init(options) // 整备接收到的这个大对象
    }
  
    function init(options = {}) {
      let {
        url,
        method = 'GET',
        data = null,
        dataType = 'JSON',
        async = true,
        cache = true,
        success,
        error
      } = options
  
      Array.from(['url', 'method', 'data', 'dataType', 'async', 'cache', 'success', 'error']).forEach(item => {
        this[item] = eval(item) // eval让字符串执行成代码
      });

      AJAX.prototype.sendAjax.call(this)
    }
  
    AJAX.prototype = {
      constructor: AJAX,
      init,
      sendAjax() {
        // 参数传递的方式、是否需要缓存
        this.handleCache()
        this.handleData()
  
        let {method, url, async, error, success} = this
        let xhr = new XMLHttpRequest()
        xhr.open(method, url, async)
        xhr.onreadystatechange = () => {
          if (xhr.readyState === 4) {
            if (!/\^(2|3)\d{2}$/.test(xhr.status)) {
              error && error(xhr.statusText, xhr)
            }
            // DATA
            let result = this.handleDataType(xhr)
            success && success(result, xhr)
          }
        }
        xhr.send()
      },
      // 整理后端返回的数据格式成我们想要的
      handleDataType(xhr) {
        let dataType = this.dataType.toUpperCase()
        let result = xhr.responseText
  
        switch(dataType) {
          case 'TEXT':
            break;
          case 'JSON':
            result = JSON.parse(result)
            break;
          case 'XML':
            result = xhr.responseXML
            break;
        }
  
        return result
      },
  
      handleCache() {
        let {url, method, cache} = this
        if (method.toUpperCase() === 'GET' && cache === false) { // 希望默认不缓存
          url += `${this.check()}=${+(new Date())}`
        }
      },
  
      check() {
        return this.url.indexOf('?') > -1 ? '&' : '?'
      },
  
      handleData() {
        let {method, data} = this
        let str = ''
        if (!data) return 
        if (typeof data === 'object') {
          for (let key in data) {
            if (data.hasOwnProperty(key)) { // 当前属性是对象自己的而不是继承得到的
              str += `${key}=${data[key]}&`
            }
          }
          data = str.substring(0, str.length)
        }
  
        if (/^(GET|DELETE|HEAD|TRACE|OPTIONS)$/i.test(method)) {
          this.url += `${this.check()}${data}`
          this.data = null
          return 
        }
  
        // post
        this.data = data
      }
    }
    init.prototype = AJAX.prototype
    window.ajax = AJAX
  })(window)